package admin

import (
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
	"time"
)

// 获取充值赠送
func RechargeList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list models.MRechargeGiveSet

	err = models.DB.Model(new(models.MRechargeGiveSet)).Where("id=?", jsonData.Id).First(&list).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list": list,
		},
	})
}

// 修改充值赠送
func RechargeAdd(c *gin.Context) {
	//获取传值
	var jsonData models.MRechargeGiveSet
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	//修改数据
	var editData = map[string]interface{}{
		"givedata": jsonData.Givedata,
		"status":   jsonData.Status,
		"caninput": jsonData.Caninput,
		"shuoming": jsonData.Shuoming,
	}
	err = models.DB.Model(new(models.MRechargeGiveSet)).Where("id=?", jsonData.ID).Updates(&editData).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10003,
			"msg":  err.Error(),
		})
		return
	}
	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，修改了充值赠送:" + strconv.Itoa(jsonData.ID) + "的内容"
	models.LogAdd(3, "修改充值赠送", userId, logData, bid, jsonData.Aid)

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 获取充值卡列表
func RechargeExchangeList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []models.MRechargeExchange
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	tx := models.DB.Model(new(models.MRechargeExchange)).Where("aid=?", jsonData.Aid)
	if jsonData.Status > 0 {
		tx = tx.Where("status=?", jsonData.Status)
	}
	if jsonData.Name != "" {
		tx = tx.Where("name LIKE ?", "%"+jsonData.Name+"%")
	}
	if jsonData.CreatedStart != "" {
		tx = tx.Where("start_time<?", define.TimeUnix(jsonData.CreatedStart))
	}
	if jsonData.CreatedEnd != "" {
		tx = tx.Where("end_time>?", define.TimeUnix(jsonData.CreatedEnd))
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("id desc").Find(&list)
	if tx.Error != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}

type MRechargeExchangeAdd struct {
	ID         int             `gorm:"type:int(10); primaryKey" json:"id"`
	Aid        int             `gorm:"type:int(10);" json:"aid"`              //账户ID
	Mid        int             `gorm:"type:int(10);" json:"mid"`              //用户id
	Name       string          `gorm:"type:varchar(255);" json:"name"`        //卡名
	CardNumber string          `json:"card_number"`                           //卡号
	HexiaoCode string          `gorm:"type:varchar(255);" json:"hexiao_code"` //唯一码 核销码
	Money      decimal.Decimal `json:"money"`                                 //充值金额
	Give       decimal.Decimal `json:"give"`                                  //赠送金额
	Status     int             `gorm:"type:int(10);" json:"status"`           //1生效;2已用；3失效
	GiveScore  int             `gorm:"type:int(10);" json:"give_score"`       //赠送积分
	IsExchange int             `gorm:"type:int(10);" json:"is_exchange"`      //是否兑换
	StartTime  int             `gorm:"type:int(10);" json:"start_time"`       //开始时间
	EndTime    int             `gorm:"type:int(10);" json:"end_time"`         //结束时间
	IsZhuan    int             `gorm:"type:int(11);" json:"is_zhuan"`         //是否转送 0为转送 1转送
	ZhuanId    string          `gorm:"type:varchar(255);" json:"zhuan_id"`    //转送用户记录id
	Remark     string          `gorm:"type:varchar(255);" json:"remark"`      //后台备注
	Num        int             `gorm:"type:int(10);" json:"num"`              //生成数量
}

// 修改充值赠送
func RechargeExchangeAdd(c *gin.Context) {
	//获取传值
	var jsonData MRechargeExchangeAdd
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	if jsonData.ID > 0 {
		//修改数据
		var editData = map[string]interface{}{
			"mid":         jsonData.Mid,
			"name":        jsonData.Name,
			"card_number": jsonData.CardNumber,
			"money":       jsonData.Money,
			"give":        jsonData.Give,
			"status":      jsonData.Status,
			"give_score":  jsonData.GiveScore,
			"start_time":  jsonData.StartTime / 1000,
			"end_time":    jsonData.EndTime / 1000,
			"remark":      jsonData.Remark,
		}
		err = models.DB.Model(new(models.MRechargeExchange)).Where("id=?", jsonData.ID).Updates(&editData).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10003,
				"msg":  err.Error(),
			})
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，修改了充值卡:" + strconv.Itoa(jsonData.ID) + "的内容"
		models.LogAdd(3, "修改充值卡", userId, logData, bid, jsonData.Aid)
	} else {
		var str string
		var data []models.MRechargeExchange
		for i := 0; i < jsonData.Num; i++ {
			//生成邀请码
			CardNumber := time.Now().Format("20060102150405")
			inviteCode1 := CardNumber + string(define.Krand(16, define.KC_RAND_KIND_UPPER))
			NewCardNumber := CardNumber + strconv.Itoa(i)
			one := models.MRechargeExchange{
				Aid:        jsonData.Aid,
				Mid:        jsonData.Mid,
				Name:       jsonData.Name,
				CardNumber: NewCardNumber,
				Money:      jsonData.Money,
				Give:       jsonData.Give,
				GiveScore:  jsonData.GiveScore,
				Status:     5,
				StartTime:  jsonData.StartTime / 1000,
				EndTime:    jsonData.EndTime / 1000,
				Remark:     jsonData.Remark,
				HexiaoCode: inviteCode1,
				CreatedAt:  int(time.Now().Unix()),
			}
			if i == 0 {
				str = jsonData.Name
			} else {
				str = str + jsonData.Name + ","
			}
			data = append(data, one)
		}
		//批量执行
		err = models.DB.Model(new(models.MRechargeExchange)).Create(&data).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10001,
				"msg":  err.Error(),
			})
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，新增了充值卡:" + str
		models.LogAdd(2, "新增充值卡", userId, logData, bid, jsonData.Aid)
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 删除充值卡
func RechargeExchangeDel(c *gin.Context) {
	var jsonData models.MRechargeExchange
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var data models.MRechargeExchange
	models.DB.Model(new(models.MRechargeExchange)).Where("id=?", jsonData.ID).First(&data)
	tx := models.DB.Begin()

	//删除
	err = tx.Delete(&models.MRechargeExchange{}, jsonData.ID).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10004,
			"msg":  err.Error(),
		})
		tx.Rollback()
		return
	}
	tx.Commit()

	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，删除了一个充值卡:" + data.Name
	models.LogAdd(4, "删除充值卡", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}
